﻿using SqlSugar;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Reflection;

namespace Microsoft.Extensions.DependencyInjection
{
    public static class SqlSugarExtension
    {
        public static SqlSugarScope AddSqlSugarSingleton(this IServiceCollection containerRegistry,DbType dbType, string connStr)
        {
            var _conStr = containerRegistry.GetConfigurtaion().GetConnectionString(connStr);
            SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
            {
                DbType = dbType,
                ConnectionString = _conStr,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute, //从特性读取主键自增信息
                MoreSettings = new ConnMoreSettings()
                {
                    PgSqlIsAutoToLower = false //数据库存在大写字段的 ，需要把这个设为false ，并且实体和字段名称要一样
                },
            },
            db =>
            {
                //单例参数配置，所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);//输出sql
                };
                db.Ado.CommandTimeOut = 30; //单位秒
            });

            containerRegistry.AddSingleton<ISqlSugarClient>(sqlSugar);
            return sqlSugar;
        }

        public static void GenerateEntity(this SqlSugarScope db)
        {
            try
            {
                string[] tables = { "tb_student_info" };

                foreach (var item in db.DbMaintenance.GetTableInfoList())
                {
                    string entityName = item.Name;
                    db.MappingTables.Add(entityName, item.Name);
                    foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
                    {
                        db.MappingColumns.Add(col.DbColumnName, col.DbColumnName, entityName);
                    }
                }

                //DB.DbFirst.IsCreateAttribute().CreateClassFile(
                //    @"D:\zj_Programs\C#file\Console\GetWebsite\GetWebsite.Core\Models\",
                //    "GetWebsite");
                
                db.DbFirst.Where(tables).IsCreateAttribute().CreateClassFile(
                @"E:\Desktop\0_models",
                    "Models");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
            }

        }

        public static void GenerateTable(this SqlSugarScope db)
        {
            try
            {
                db.DbMaintenance.CreateDatabase();
                db.CodeFirst.SetStringDefaultLength(200).InitTables(
                    //tables
                    );
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"{ex}");
            }
        }

    }
}
